package org.xshop.service.impl;

import java.util.Date;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.transaction.annotation.Transactional;
import org.xshop.mapper.THotSearchMapper;
import org.xshop.model.THotSearch;
import org.xshop.service.ITHotSearchService;

import com.weibo.api.motan.config.springsupport.annotation.MotanService;

import top.ibase4j.core.base.BaseServiceImpl;
import top.ibase4j.core.support.generator.Sequence;
import top.ibase4j.core.util.CacheUtil;

/**
 * <p>
 * 热搜  服务实现类
 * </p>
 *
 * @author ShenHuaJie
 * @since 2018-03-01
 */
@MotanService(interfaceClass = ITHotSearchService.class)
@CacheConfig(cacheNames = "THotSearch")
public class HotSearchService extends BaseServiceImpl<THotSearch, THotSearchMapper> implements ITHotSearchService {
    @Override
    @Transactional
    public THotSearch update(THotSearch record) {
        THotSearch result = selectOne(record);
        record.setUpdateTime(new Date());
        if (result == null || result.getId() == null) {
            result.setTimes(1L);
            return super.update(record);
        } else {
            String requestId = Sequence.next().toString();
            String lockKey = getLockKey("ADD" + record.getId());
            if (CacheUtil.getLock(lockKey, requestId)) {
                try {
                    result.setTimes(result.getTimes() + 1);
                    return super.update(record);
                } finally {
                    CacheUtil.unLock(lockKey, requestId);
                }
            } else {
                return update(record);
            }
        }
    }
}
